﻿namespace PengSW.XmlTools
{
    /// <summary>
    /// 支持Xml序列化的对象接口
    /// </summary>
    public interface IXmlSeriable
    {
        /// <summary>
        /// 从Xml结点中恢复对象
        /// </summary>
        /// <param name="aXmlNode">源结点</param>
        void ReadFromXml(System.Xml.XmlNode aXmlNode);

        /// <summary>
        /// 将对象保存到Xml结点中
        /// </summary>
        /// <param name="aXmlNode">目标结点</param>
        void WriteToXml(System.Xml.XmlNode aXmlNode);
    }

    /// <summary>
    /// 支持Xml序列化的对象列表
    /// </summary>
    /// <typeparam name="T">列表元素类型，必须是IXmlSeriable的派生类</typeparam>
    public class XmlSeriableList<T> : System.Collections.Generic.List<T>, IXmlSeriable where T : class, IXmlSeriable
    {
        #region IXmlSeriable 成员

        public virtual void ReadFromXml(System.Xml.XmlNode aXmlNode)
        {
            this.Clear();
            if (aXmlNode == null) return;

            // 列表中的元素保存在Member子结点中
            foreach (System.Xml.XmlNode aMemberNode in aXmlNode.SelectNodes("Member"))
            {
                T aObject = XmlTools.CreateObjectFromXml<T>(aMemberNode);
                if (aObject == null) continue;
                aObject.ReadFromXml(aMemberNode);
                Add(aObject);
            }
        }

        public virtual void WriteToXml(System.Xml.XmlNode aXmlNode)
        {
            if (aXmlNode == null) return;
            this.WriteTypeToXml(aXmlNode);
            foreach (IXmlSeriable aObject in this)
            {
                System.Xml.XmlNode aObjectNode = aXmlNode.CreateChildNode("Member");
                aObject.WriteTypeToXml(aObjectNode);
                aObject.WriteToXml(aObjectNode);
            }
        }

        #endregion
    }
}
